// LoginActivity.java
package com.tzkyzj.tiremanagersystem.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.tzkyzj.tiremanagersystem.R;
import com.tzkyzj.tiremanagersystem.api.AuthApiService;
import com.tzkyzj.tiremanagersystem.network.ApiClient;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity {

    private EditText etUsername, etPassword;
    private Button btnLogin;
    private ProgressBar progressBar;
    private AuthApiService authApiService;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 确保 ApiClient 使用正确的 Context
        ApiClient.getClient();
        initViews();
        setupRetrofit();
        checkAutoLogin();
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        progressBar = findViewById(R.id.progress_bar);

        btnLogin.setOnClickListener(v -> attemptLogin());

        // 测试用，方便快速登录
        //etUsername.setText("admin");
        //etPassword.setText("123456");
    }

    private void setupRetrofit() {
        // 使用统一的 ApiClient
        Retrofit retrofit = ApiClient.getClient();
        if (retrofit != null) {
            authApiService = retrofit.create(AuthApiService.class);
            Log.d("LoginActivity", "使用统一的 ApiClient 配置");
        } else {
            Log.e("LoginActivity", "ApiClient 初始化失败");
            Toast.makeText(this, "网络初始化失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void checkAutoLogin() {
        sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
        String username = sharedPreferences.getString("username", null);

        Log.d("LoginActivity", "自动登录检查 - 用户名: " + username);

        if (username != null && !username.isEmpty()) {
            Log.d("LoginActivity", "发现已保存的用户名，验证服务器 Session");

            // 验证服务器 Session 是否仍然有效
            verifyAutoLoginSession();
        } else {
            Log.d("LoginActivity", "没有保存的用户信息，显示登录界面");
        }
    }

    /**
     * 验证自动登录的 Session
     */
    private void verifyAutoLoginSession() {
        Retrofit retrofit = ApiClient.getClient();
        if (retrofit == null) {
            Log.e("LoginActivity", "ApiClient 不可用，需要重新登录");
            return;
        }

        AuthApiService authApiService = retrofit.create(AuthApiService.class);
        Call<Map<String, Object>> call = authApiService.getUserInfo();
        call.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Map<String, Object> data = response.body();
                    Boolean authenticated = (Boolean) data.get("authenticated");

                    if (authenticated != null && authenticated) {
                        // Session 有效，执行自动登录
                        Log.d("LoginActivity", "自动登录 Session 验证成功");
                        performAutoLogin();
                    } else {
                        // Session 无效，清除本地数据
                        Log.e("LoginActivity", "自动登录 Session 无效");
                        clearAutoLoginData();
                    }
                } else {
                    // Session 无效
                    Log.e("LoginActivity", "自动登录 Session 验证失败: " + response.code());
                    clearAutoLoginData();
                }
            }

            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
                Log.e("LoginActivity", "自动登录 Session 验证网络错误: " + t.getMessage());
                // 网络问题，保守起见不自动登录
            }
        });
    }

    /**
     * 执行自动登录跳转
     */
    private void performAutoLogin() {
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        String username = prefs.getString("username", "");
        String role = prefs.getString("role", "");
        boolean shouldReturnToUserManagement = prefs.getBoolean("should_return_to_user_management", false);

        Log.d("LoginActivity", "自动登录: 用户名=" + username + ", 角色=" + role +
                ", 返回用户管理=" + shouldReturnToUserManagement);

        if (shouldReturnToUserManagement && "ADMIN".equals(role)) {
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("should_return_to_user_management", false);
            editor.apply();

            Log.d("LoginActivity", "自动跳转到用户管理页面");
            Intent intent = new Intent(LoginActivity.this, UserManagementActivity.class);
            startActivity(intent);
        } else {
            if (shouldReturnToUserManagement) {
                Log.d("LoginActivity", "需要返回用户管理但用户不是管理员，清除标志");
                SharedPreferences.Editor editor = prefs.edit();
                editor.putBoolean("should_return_to_user_management", false);
                editor.apply();
            }
            Log.d("LoginActivity", "自动跳转到轮胎列表页面");
            Intent intent = new Intent(LoginActivity.this, TireListActivity.class);
            startActivity(intent);
        }
        finish();
    }

    /**
     * 清除自动登录数据
     */
    private void clearAutoLoginData() {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
        ApiClient.clearClient();
        Log.d("LoginActivity", "已清除过期的自动登录数据");
    }

    private void attemptLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (username.isEmpty()) {
            etUsername.setError("请输入用户名");
            return;
        }

        if (password.isEmpty()) {
            etPassword.setError("请输入密码");
            return;
        }

        if (password.length() < 6) {
            etPassword.setError("密码长度不能少于6位");
            return;
        }

        login(username, password);
    }

    private void login(String username, String password) {
        setLoading(true);

        Map<String, String> loginData = new HashMap<>();
        loginData.put("username", username);
        loginData.put("password", password);
        loginData.put("deviceType", "ANDROID");

        Call<Map<String, Object>> call = authApiService.login(loginData);
        call.enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
                setLoading(false);

                if (response.isSuccessful() && response.body() != null) {
                    Map<String, Object> responseData = response.body();
                    Boolean success = (Boolean) responseData.get("success");

                    if (success != null && success) {
                        // 登录成功
                        handleLoginSuccess(responseData, username);
                    } else {
                        String message = (String) responseData.get("message");
                        showError(message != null ? message : "登录失败");
                    }
                } else {
                    showError("登录失败，请检查网络连接");
                }
            }

            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
                setLoading(false);
                showError("网络连接失败: " + t.getMessage());
                Log.e("LoginActivity", "Login failed", t);
            }
        });
    }

    private void handleLoginSuccess(Map<String, Object> responseData, String username) {
        try {
            // 保存登录信息
            sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            // 保存用户基本信息
            editor.putString("username", username);

            // 保存用户角色信息
            Map<String, Object> userInfo = (Map<String, Object>) responseData.get("userInfo");
            if (userInfo != null) {
                String role = (String) userInfo.get("role");
                if (role != null) {
                    editor.putString("role", role);
                }

                // 从transportCompany字段获取公司信息
                String company = (String) userInfo.get("transportCompany");
                if (company != null) {
                    editor.putString("company", company);
                    Log.d("LoginActivity", "保存公司信息: " + company);
                } else {
                    Log.w("LoginActivity", "用户信息中没有transportCompany字段");
                    company = inferCompanyFromUsername(username);
                    editor.putString("company", company);
                    Log.d("LoginActivity", "推断公司信息: " + company);
                }

                // 从vehiclePlateNumber字段获取车牌信息
                String plateNumber = (String) userInfo.get("vehiclePlateNumber");
                if (plateNumber != null) {
                    editor.putString("plateNumber", plateNumber);
                    Log.d("LoginActivity", "保存车牌信息: " + plateNumber);
                } else {
                    Log.w("LoginActivity", "用户信息中没有vehiclePlateNumber字段");
                    plateNumber = "未设置";
                    editor.putString("plateNumber", plateNumber);
                    Log.d("LoginActivity", "设置默认车牌: " + plateNumber);
                }

                // 打印完整的用户信息用于调试
                Log.d("LoginActivity", "完整的用户信息: " + userInfo.toString());
            } else {
                Log.e("LoginActivity", "用户信息为空");
                String company = inferCompanyFromUsername(username);
                editor.putString("company", company);
                editor.putString("plateNumber", "未设置");
                Log.d("LoginActivity", "用户信息为空，设置默认公司: " + company);
            }

            editor.apply();

            // === 关键修改：移除清除 Cookie 的代码 ===
            // 不要清除 Cookie！登录成功的 Cookie 需要保留用于后续请求
            // ApiClient.clearClient();  // 注释掉这行
            // Log.d("LoginActivity", "已清除旧 ApiClient 实例");  // 注释掉这行

            // === 关键修改：也不需要重新创建 ApiClient ===
            // setupRetrofit();  // 注释掉这行
            // Log.d("LoginActivity", "已重新创建 ApiClient");  // 注释掉这行

            // 调试 Session 状态
            ApiClient.debugCookies();  // 添加这行来验证 Cookie 状态

            // 打印保存的所有用户信息用于调试
            Log.d("LoginActivity", "=== 保存的用户信息 ===");
            Log.d("LoginActivity", "用户名: " + username);
            Log.d("LoginActivity", "角色: " + sharedPreferences.getString("role", "未知"));
            Log.d("LoginActivity", "公司: " + sharedPreferences.getString("company", "未知"));
            Log.d("LoginActivity", "车牌: " + sharedPreferences.getString("plateNumber", "未知"));

            // 检查是否需要返回用户管理页面
            boolean shouldReturnToUserManagement = sharedPreferences.getBoolean("should_return_to_user_management", false);

            Log.d("LoginActivity", "登录成功，是否需要返回用户管理: " + shouldReturnToUserManagement);

            if (shouldReturnToUserManagement && "ADMIN".equals(sharedPreferences.getString("role", ""))) {
                // 清除标志
                SharedPreferences.Editor clearEditor = sharedPreferences.edit();
                clearEditor.putBoolean("should_return_to_user_management", false);
                clearEditor.apply();

                Log.d("LoginActivity", "跳转到用户管理页面");
                Intent intent = new Intent(LoginActivity.this, UserManagementActivity.class);
                startActivity(intent);
            } else {
                if (shouldReturnToUserManagement) {
                    Log.d("LoginActivity", "需要返回用户管理但用户不是管理员");
                    Toast.makeText(this, "当前用户不是管理员，无法访问用户管理", Toast.LENGTH_LONG).show();

                    SharedPreferences.Editor clearEditor = sharedPreferences.edit();
                    clearEditor.putBoolean("should_return_to_user_management", false);
                    clearEditor.apply();
                }
                Log.d("LoginActivity", "跳转到轮胎列表页面");
                Intent intent = new Intent(LoginActivity.this, TireListActivity.class);
                startActivity(intent);
            }

            finish();

        } catch (Exception e) {
            Log.e("LoginActivity", "Error handling login success", e);
            showError("处理登录信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据用户名推断公司信息（备用方案）
     */
    private String inferCompanyFromUsername(String username) {
        if (username == null) return "未知公司";

        // 简单的推断逻辑，根据实际情况调整
        if (username.contains("gongsi") || username.contains("company")) {
            return username.replace("01", "").replace("02", "").replace("03", "") + "公司";
        }
        if (username.contains("admin")) {
            return "管理员公司";
        }
        if (username.contains("driver") || username.contains("siji")) {
            return username + "所属公司";
        }

        return username + "公司";
    }

    private void setLoading(boolean loading) {
        progressBar.setVisibility(loading ? View.VISIBLE : View.GONE);
        btnLogin.setEnabled(!loading);
        btnLogin.setText(loading ? "登录中..." : "登录");
    }

    private void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
}